package com.smartcampusbackend.service.impl;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePrecreateResponse;
import com.alipay.easysdk.payment.common.models.AlipayTradeQueryResponse;
import com.smartcampusbackend.service.AlipayService;
import com.smartcampusbackend.service.PaymentOrderService;
import com.smartcampusbackend.model.PaymentOrder;
import com.smartcampusbackend.util.AlipayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.HashMap;

@Service
public class AlipayServiceImpl implements AlipayService {
    @Autowired
    private PaymentOrderService paymentOrderService;
    @Autowired
    private AlipayUtil alipayUtil;

    @Override
    public Map<String, Object> createPayment(String outTradeNo, String subject, String totalAmount) {
        Map<String, Object> result = new HashMap<>();
        try {
            AlipayTradePrecreateResponse response = Factory.Payment.FaceToFace().preCreate(subject, outTradeNo, totalAmount);

            if ("10000".equals(response.getCode())) {
                result.put("success", true);
                result.put("qrCode", response.getQrCode());
                result.put("outTradeNo", outTradeNo);
                result.put("subject", subject);
                result.put("totalAmount", totalAmount);
                result.put("message", "请使用支付宝扫码支付");
            } else {
                result.put("success", false);
                result.put("message", "支付宝下单失败: " + response.getMsg());
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("异常信息: " + e.getMessage());
            if (e.getCause() != null) {
                System.out.println("Cause: " + e.getCause().getMessage());
            }
            result.put("success", false);
            result.put("message", "支付宝接口调用异常: " + e.getMessage());
        }
        return result;
    }

    @Override
    public boolean verifyCallback(Map<String, String> params) {
        try {
            // 使用 easysdk 推荐的验签方式
            return Factory.Payment.Common().verifyNotify(params);
        } catch (Exception e) {
            System.err.println("支付宝回调签名验证失败: " + e.getMessage());
            return false;
        }
    }

    @Override
    public boolean handlePaymentSuccess(String outTradeNo, String tradeNo, String totalAmount) {
        boolean success = paymentOrderService.payOrder(outTradeNo, "alipay");
        if (success) {
            PaymentOrder order = paymentOrderService.getOrderByOrderNo(outTradeNo);
            if (order != null) {
                // 可扩展：保存tradeNo等信息
                return true;
            }
        }
        return false;
    }

    @Override
    public Map<String, Object> queryOrderStatus(String outTradeNo) {
        Map<String, Object> result = new HashMap<>();
        try {
            AlipayTradeQueryResponse response = Factory.Payment.Common().query(outTradeNo);
            if ("10000".equals(response.getCode())) {
                result.put("success", true);
                result.put("tradeStatus", response.getTradeStatus());
                result.put("tradeNo", response.getTradeNo());
                result.put("totalAmount", response.getTotalAmount());
                result.put("buyerId", response.getBuyerUserId());
            } else {
                result.put("success", false);
                result.put("message", "查询失败: " + response.getMsg());
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常: " + e.getMessage());
        }
        return result;
    }

    @Override
    public String getAppId() { return alipayUtil.getAppId(); }
    @Override
    public String getGatewayUrl() { return alipayUtil.getGatewayUrl(); }
    @Override
    public String getNotifyUrl() { return alipayUtil.getNotifyUrl(); }
}